package demo1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-09-06
 * Time: 19:53
 */
public class Test {

    public static List<Integer> findSubstring(String s, String[] words) {
        int len = words[0].length(), m = words.length;
        List<Integer> list = new ArrayList<>();
        Map<String, Integer> hash = new HashMap<>();
        for(String s1 : words){
            hash.put(s1, (hash.getOrDefault(s1, 0) + 1));
        }

        for(int i = 0; i < len; i++){
            Map<String, Integer> hash1 = new HashMap<>();
            for(int left = i, right = i, count = 0; right + len <= s.length(); right += len){
                String str = s.substring(right, right + len);
                hash1.put(str, (hash1.getOrDefault(str, 0) + 1));

                if(hash1.get(str) <= hash.getOrDefault(str, 0)){
                    count++;
                }

                if(right - left + 1 > len * m){
                    String s1 = s.substring(left, len + left);
                    if(hash1.get(s1) <= hash.getOrDefault(s1, 0)){
                        count--;
                    }
                    hash1.put(s1, hash1.get(s1) - 1);
                    left += len;
                }

                if(count == m){
                    list.add(left);
                }
            }
        }
        return list;
    }

    public static void main(String[] args) {
        String[] strings = {"foo","bar"};
        findSubstring("barfoothefoobarman", strings);
    }
}
